import { useCurrentElement } from '@vueuse/core'
import elementResizeDetectorMaker from 'element-resize-detector'
import { debounce } from 'lodash-es'
import { CHART_SYMBOL } from '@/symbol'

export function useChartResize(name: string) {
  const router = useRouter()
  const [resizeStatus, setResizeStatus] = useState(false)

  /**
   */
  const isCurrent = computed(
    () => router.currentRoute.value.path === name,
  )
  /** 控制自动监听页面大小 */
  const autoResizeEnabled = (callback?: () => void) => {
    const erd = elementResizeDetectorMaker()
    const el = useCurrentElement()
    erd.listenTo(
      el.value,
      debounce(() => {
        if (!isCurrent.value)
          return
        callback?.()
        handlerResize()
      }, 200),
    )
    onActivated(
      debounce(() => {
        if (!isCurrent.value)
          return
        callback?.()
        handlerResize()
      }, 300),
    )
  }
  const handlerResize = async () => {
    await nextTick()
    setResizeStatus(true)
    await nextTick()
    setResizeStatus(false)
  }

  provide(CHART_SYMBOL.RESIZE_ENABLE, autoResizeEnabled)
  provide(CHART_SYMBOL.RESIZE_STATUS, resizeStatus)
  provide(CHART_SYMBOL.RESIZE_TRIGGER, handlerResize)
}
